package com.maoxs.service;

import com.maoxs.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@CacheConfig(cacheNames = "myuser")
@Slf4j
public class UserService {

    public static final Map<Long, User> users = new HashMap<>();

    static {
        users.put(1L, new User(1L, "我是快乐鱼"));
        users.put(2L, new User(1L, "我是忧郁猫"));
        users.put(3L, new User(1L, "我是昴先生"));
    }

    @Autowired
    private JCacheCacheManager jCacheCacheManager;

    public void getUserByManager() {
        Cache cache = jCacheCacheManager.getCache("myuser");
        User user = new User(1L, "我是快乐鱼");
        cache.put(1L, user);
    }


    /**
     * 使用自定义的key
     *
     * @param id
     * @return
     */
    @Cacheable(keyGenerator = "wiselyKeyGenerator")
    public User getUserKeyGen(Long id) {
        log.info("这是自定义key，ehcahe里没有从map中读取");
        return users.get(id);
    }

    /**
     * 从缓存中读取否则读map
     *
     * @param id
     * @return
     */
    @Cacheable(key = "#id")
    public User getUser(Long id) {
        log.info("ehcahe中没有，从map中读取");
        return users.get(id);
    }

    /**
     * 将方法的返回值放到缓存中
     * 在方法的调用前并不会检查缓存，方法始终都会被调用。
     *
     * @param user
     */
    @CachePut(key = "#id")
    public User saveOrUpdate(Long id, User user) {
        log.info("进入 saveOrUpdate 方法");
        users.put(id, user);
        return users.get(id);
    }

    /**
     * 清除缓存
     *
     * @param id
     */
    @CacheEvict(key = "#id")
    public void delete(Long id) {
        users.remove(id);
        log.info("进入 delete 方法");
    }


}

